# backend/app.py
from flask import Flask, request, jsonify
from flask_cors import CORS
# 移除JWT相关的导入
from backend.config import Config
from backend.extensions import db, bcrypt, celery
from backend.api.auth import auth_bp
from backend.api.main import main_bp
from backend.api.admin import admin_bp

def create_app():
    app = Flask(__name__, static_folder='../frontend', static_url_path='')
    app.config.from_object(Config)
    
    # 初始化扩展
    db.init_app(app)
    bcrypt.init_app(app)
    CORS(app)
    
    # 初始化Celery
    celery.conf.update(
        broker_url=app.config['CELERY_BROKER_URL'],
        result_backend=app.config['CELERY_RESULT_BACKEND']
    )
    
    # 注册蓝图
    app.register_blueprint(auth_bp, url_prefix='/api/auth')
    app.register_blueprint(main_bp, url_prefix='/api')
    app.register_blueprint(admin_bp, url_prefix='/api/admin')
    
    # 添加根路径路由，返回前端页面
    @app.route('/')
    def index():
        return app.send_static_file('public/index.html')
    
    # 处理前端路由，使Vue Router的history模式能正常工作
    @app.errorhandler(404)
    def serve_frontend(e):
        # 对于非API请求，返回前端应用
        if not request.path.startswith('/api'):
            return app.send_static_file('public/index.html')
        # API请求返回原始错误
        return e
    
    return app

app = create_app()

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True)